package com.siqi.hr.system.common.sql;

import com.siqi.hr.system.common.chan.BeSql;
import org.apache.commons.lang.StringUtils;

public class STable implements BeSql {
	public static final String TABLE_HEAD = "t_";
	private String[] separations;
	/**
	 * 关联表名
	 */
	private String name;
	
	/**
	 * 关联表别名
	 */
	private String byName;
	
	/**
	 * 主表别名
	 */
	private String ofByName;
	
	/**
	 * 连接表方式(left join、right join、inner join)
	 */
	private TableJoinType tableJoinType = TableJoinType.left;

	public STable(String name) {
		validaty(name);
		this.name = name;
		this.separations = name.split("_");
	}

	public STable(String name, String byName) {
		validaty(name);
		this.name = name;
		this.separations = name.split("_");
		this.byName = byName;
	}

	public STable(String name, String byName, String ofByName) {
		validaty(name);
		this.name = name;
		this.separations = name.split("_");
		this.byName = byName;
		this.ofByName = ofByName;
	}

	public String getOfByName() {
		if (this.ofByName == null) {
			return getByName();
		}
		return this.ofByName;
	}

	public void setOfByName(String ofByName) {
		this.ofByName = ofByName;
	}

	public String getByName() {
		if (this.byName == null) {
			return this.name;
		}
		return this.byName;
	}

	public void setByName(String byName) {
		this.byName = byName;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	protected void validaty(String name) {
	}

	public boolean isSysTemEntity() {
		return "sys".equals(this.separations[0]);
	}

	public boolean hasType() {
		return "type".equals(this.separations[1]);
	}

	public int getEntityId() {
		if (StringUtils.startsWithIgnoreCase(getName(), "z_")) {
			return 0;
		}
		return Integer.parseInt(this.separations[1]);
	}

	public StringBuilder toSqlString() {
		StringBuilder sb = null;

		sb = new StringBuilder(this.name + " as " + getByName());

		return sb;
	}

	public boolean equals(Object obj) {
		if ((obj != null) && (this.name != null) && ((obj instanceof STable))
				&& (this.name.equals(((STable) obj).getName()))
				&& (getByName().equals(((STable) obj).getByName()))) {
			return true;
		}
		return false;
	}

	public int hashCode() {
		return this.name.hashCode();
	}

	public String toString() {
		return this.name;
	}

	public boolean isPk() {
		boolean pk = "PK".equals(this.separations[0].toUpperCase());

		return pk;
	}

	public TableJoinType getTableJoinType() {
		return this.tableJoinType;
	}

	public void setTableJoinType(TableJoinType tableJoinType) {
		this.tableJoinType = tableJoinType;
	}
}
